package com.jdbc.dao;

import com.jdbc.pojo.Account;
import com.jdbc.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class StudentDaoImpl implements StudentDao{

@Autowired
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    @Override
    public Student findUsernameAndPassword(String username, String password) {
        String sql = "select * from student where username=? and password=?";
        Student student=null;
//        student = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Student.class), username, password);
//        student = null;
        try {
            student = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Student.class), username, password);
        } catch (Exception e) {

        }
        return student;
    }

    @Override
    public int addStudent(Student student) {
        String sql="insert student (username,password,course) values(?,?,?)";
        Object params[] =new Object[]{student.getUsername(),student.getPassword(),student.getCourse()};
        int n= jdbcTemplate.update(sql,params);
        return n;

    }

    @Override
    public int updateStudentById(Student student) {
        String sql="update student set username=?,password=?,course=? where id=?";
        Object params[] =new Object[]{student.getUsername(),student.getPassword(),student.getCourse(),student.getId()};
        int n= jdbcTemplate.update(sql,params);
        return n;
    }

    @Override
    public int deleteStudentById(int id) {
        String sql="delete from student where id=?";
        int n = jdbcTemplate.update(sql, id);
        return n;
    }

    @Override
    public Student findById(int id) {
        String sql="select * from student where id=?";
        RowMapper<Student> rowMapper=new BeanPropertyRowMapper<>(Student.class);
        Student student=null;
        try{
            student=jdbcTemplate.queryForObject(sql,rowMapper,id);
        }catch (Exception e){

        }
        return student;
    }
}

